//
//  GWComposeViewController.m
//  新浪微博
//
//  Created by qianfeng on 16/1/12.
//  Copyright (c) 2016年 高炜. All rights reserved.
//

#import "GWComposeViewController.h"
#import "GWEmotionTextView.h"
#import "GWMyInputToolBar.h"
#import "GWComposePhotoView.h"
#import "GWAccountTool.h"
#import "GWAccount.h"
#import "MBProgressHUD+MJ.h"
#import "GWStatuseTool.h"
#import "GWEmotionKeybordView.h"
#import "GWEmotion.h"

#import "AFHTTPRequestOperationManager.h"
@interface GWComposeViewController ()<UITextViewDelegate,GWMyInputToolBarDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic,weak)GWEmotionTextView *textView;
@property (nonatomic,weak)GWMyInputToolBar *toolBar;
@property (nonatomic,weak)GWComposePhotoView *photoView;

@property (nonatomic,strong)GWEmotionKeybordView *emotionKeybord;

@property(nonatomic,assign,getter=isChangeEmotionKeybord)BOOL changeEmotionKeybord;
@end

@implementation GWComposeViewController
-(GWEmotionKeybordView *)emotionKeybord
{
  
    if (_emotionKeybord ==nil) {
        self.emotionKeybord =[GWEmotionKeybordView keybord];
        self.emotionKeybord.width =GWScreenW;
        self.emotionKeybord.height =216;
        
    }
    return _emotionKeybord;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNavgationBar];
    [self setTextView];
    
    [self setpohotView];
    [self setToolBar];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didSelectedEmotion:) name:GWEmotionDidSelectedNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didClickDelete) name:GWEmotionClickDeleteBtnNotification object:nil];
    // Do any additional setup after loading the view.
}
-(void)didClickDelete
{
    
    [self.textView deleteBackward];
}
//选中表情的通知
-(void)didSelectedEmotion:(NSNotification *)note
{
    GWEmotion *emotion =note.userInfo[GWDidSelectedEmotion];
    
    [self.textView addEmotion:emotion];
    
    [self textViewDidChange:self.textView];
}
-(void)setpohotView
{
    GWComposePhotoView *photoView =[[GWComposePhotoView alloc]init];
    photoView.frame =self.textView.frame;
    photoView.y =100;
    [self.textView addSubview:photoView];
    self.photoView =photoView;
}

#pragma mark ToolBarFoundation
-(void)setToolBar
{
    GWMyInputToolBar *toolBar =[[GWMyInputToolBar alloc]init];
    self.toolBar =toolBar;	
    toolBar.delegate =self;
    [self.view addSubview:toolBar];
}
-(void)myToolBar:(GWMyInputToolBar *)toolBar didClickBtn:(InputToolBarButtonType)type
{
   
    switch (type) {
        case InputToolBarButtonTypeCamera:
            [self camera];
            break;
        case InputToolBarButtonTypePicture:
            [self picture];
            break;
        case InputToolBarButtonTypeEmotion:
            [self emotion];
            break;
            
        default:
            break;
    }
}
-(void)camera
{
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])return;
    
    UIImagePickerController *pc =[[UIImagePickerController alloc]init];
    pc.sourceType =UIImagePickerControllerSourceTypeCamera;
    pc.delegate =self;
    [self presentViewController:pc animated:YES completion:nil];
}
-(void)picture
{
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum])return;
    
    UIImagePickerController *pc =[[UIImagePickerController alloc]init];
    pc.sourceType =UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    pc.delegate =self;
    [self presentViewController:pc animated:YES completion:nil];
}
-(void)emotion
{
    self.changeEmotionKeybord =YES;
    if (self.textView.inputView) {//emotion键盘
        self.textView.inputView =nil;
        self.toolBar.emotionKeybord =YES;
        
    }else
    {
        self.toolBar.emotionKeybord =NO;
        self.textView.inputView =self.emotionKeybord;
    }
    
    [self.textView resignFirstResponder];
    
    self.changeEmotionKeybord=NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.textView becomeFirstResponder];
    });
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image =info[UIImagePickerControllerOriginalImage];
    [self.photoView addImage:image];
    [picker dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark TextViewFoundation
-(void)setTextView
{
    GWEmotionTextView *textView =[[GWEmotionTextView alloc]init];
    textView.frame =self.view.bounds;
    textView.font =[UIFont systemFontOfSize:14];
    textView.placeholder =@"分享新鲜事...";
    textView.delegate =self;
    [self.view addSubview:textView];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardWillhidden:) name:UIKeyboardWillHideNotification object:nil];
    self.textView =textView;
}
-(void)keyBoardWillShow:(NSNotification *)sender
{
   
    CGFloat animationTime = [sender.userInfo[UIKeyboardAnimationDurationUserInfoKey]doubleValue];
    CGRect keybordFrame =[sender.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];
   
    [UIView animateWithDuration:animationTime animations:^{
        self.toolBar.transform =CGAffineTransformMakeTranslation(0, -keybordFrame.size.height);
    }];
}
-(void)keyBoardWillhidden:(NSNotification *)sender
{
    if (self.isChangeEmotionKeybord) return;
    CGFloat animationTime = [sender.userInfo[UIKeyboardAnimationDurationUserInfoKey]doubleValue];
    
    [UIView animateWithDuration:animationTime animations:^{
        self.toolBar.transform =CGAffineTransformIdentity;
    }];
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    
    [self.textView resignFirstResponder];
}
-(void)textViewDidChange:(UITextView *)textView
{
    self.navigationItem.rightBarButtonItem.enabled = textView.attributedText.length>0;
}

#pragma mark NavgationBarFoundation
-(void)setNavgationBar
{
    NSString *name =[GWAccountTool Account].username;
    if (name) {
        NSString *sendWeibo =@"发微博";
        NSString *string =[NSString stringWithFormat:@"%@\n%@",sendWeibo,name];
        NSMutableAttributedString *attString =[[NSMutableAttributedString alloc]initWithString:string];
        [attString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} range:[string rangeOfString:sendWeibo]];
        [attString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12]} range:[string rangeOfString:name]];
        [attString addAttributes:@{NSForegroundColorAttributeName:[UIColor lightGrayColor]} range:[string rangeOfString:name]];
        UILabel *label =[[UILabel alloc]init];
        label.attributedText =attString;
        label.width =200;
        label.height =44;
        label.numberOfLines =0;
        label.textAlignment =NSTextAlignmentCenter;
        
        self.navigationItem.titleView =label;
    }
   else
   {
       self.navigationItem.title =@"发微博";
   }
    self.view.backgroundColor =[UIColor whiteColor];
    self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancelOnTouch)];
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc]initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(sentOnTouch)];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationItem.rightBarButtonItem.enabled = NO;
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self.textView becomeFirstResponder];
}
-(void)cancelOnTouch
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)sentOnTouch
{
    if (self.photoView.images.count) {
        [self sentStatuseWithPic];
    }
    else
    {
        [self sentStatuseWithoutPic];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)sentStatuseWithPic
{
    
    AFHTTPRequestOperationManager *manager=[[AFHTTPRequestOperationManager alloc]init];
    NSMutableDictionary *parameter =[NSMutableDictionary dictionary];
    parameter[@"access_token"] =[GWAccountTool Account].access_token;
    parameter[@"status"]=self.textView.text;
    
    [manager POST:@"https://upload.api.weibo.com/2/statuses/upload.json" parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        UIImage *image =[self.photoView.images firstObject];
        NSData *data =UIImageJPEGRepresentation(image, 0.2);
        [formData appendPartWithFileData:data name:@"pic" fileName:@"test.jpg" mimeType:@"image/jpeg"];
    }  success:^(AFHTTPRequestOperation *operation, NSDictionary* statuse) {
        [MBProgressHUD showSuccess:@"发表成功"];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD showError:@"发表失败"];
        NSLog(@"%@",error);
    }];
    
    
}
-(void)sentStatuseWithoutPic
{
    GWSendStatuseParam *parameter =[GWSendStatuseParam param];
    parameter.status=self.textView.realText;
    [GWStatuseTool sendStatuseWithParame:parameter success:^(GWSendStatuseResult *result) {
        [MBProgressHUD showSuccess:@"发表成功"];
    } failure:^(NSError *error) {
        [MBProgressHUD showError:@"发表失败"];
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
